package com.binarysoft.service.common.quartz;

import static org.quartz.CronScheduleBuilder.cronSchedule;
import static org.quartz.JobBuilder.newJob;
import static org.quartz.TriggerBuilder.newTrigger;

import org.quartz.CronTrigger;
import org.quartz.Job;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.SchedulerFactory;
import org.quartz.Trigger;
import org.quartz.impl.StdSchedulerFactory;

import common.framework.dsb.AbstractServiceBean;
import common.framework.dsb.annotation.DSBService;
import common.framework.dsb.service.ServiceContext;

@DSBService(name = "DSB/QuartzService")
public class QuartzServiceBean extends AbstractServiceBean implements QuartzService {
	private Scheduler scheduler = null;
	private SchedulerFactory schedulerFactory = null;

	@Override
	public void start(ServiceContext serviceContext) throws Exception {
		super.start(serviceContext);

		serviceContext.loadConfigProperties("quartz.properties");
		String threadCount = serviceContext.getProperty("org.quartz.threadPool.threadCount");
		System.setProperty("org.quartz.threadPool.threadCount", threadCount);

		schedulerFactory = new StdSchedulerFactory();
		scheduler = schedulerFactory.getScheduler();
		scheduler.start();
	}

	@Override
	public void refresh() throws Exception {
	}

	@Override
	public void close() throws Exception {
		scheduler.shutdown(true);
	}

	@Override
	public long scheduleJob(Class<? extends Job> jobClass, String cronExpression) throws Exception {
		long jobID = System.nanoTime();
		JobDetail jobDetail = newJob(jobClass).withIdentity("job-" + jobID, "group1").usingJobData(JOB_ID, jobID).build();
		CronTrigger trigger = newTrigger().withIdentity("trigger-" + jobID, "group1").withSchedule(cronSchedule(cronExpression)).build();
		scheduleJob(jobDetail, trigger);
		return jobID;
	}

	@Override
	public void scheduleJob(JobDetail jobDetail, Trigger trigger) throws SchedulerException {
		scheduler.scheduleJob(jobDetail, trigger);
	}

	@Override
	public SchedulerFactory getSchedulerFactory() {
		return schedulerFactory;
	}

	@Override
	public Scheduler getScheduler() {
		return scheduler;
	}

}
